from typing import *


class Solution:
    def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
        n = len(nums1)

        def f(m1, m2, b):
            s = b
            for i in range(n - 1):
                a, b = nums1[i], nums2[i]
                if a > m1 or b > m2:
                    if a <= m2 and b <= m1:
                        s += 1
                    else:
                        return -1
            return s

        a1 = f(nums1[n - 1], nums2[n - 1], 0)
        a2 = f(nums2[n - 1], nums1[n - 1], 1)
        print(a1, a2)
        if a1 == -1 and a2 == -1:
            return -1
        if a1 == -1:
            return a2
        if a2 == -1:
            return a1
        return min(a1, a2)


s = Solution()
print(s.minOperations(nums1=[1, 2, 7], nums2=[4, 5, 3]))


from math import inf


class Solution:
    def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
        def f(last1: int, last2: int) -> int:
            res = 0
            for x, y in zip(nums1, nums2):
                if x > last1 or y > last2:
                    if y > last1 or x > last2:
                        return inf
                    res += 1
            return res

        ans = min(f(nums1[-1], nums2[-1]), f(nums2[-1], nums1[-1]))
        return ans if ans < inf else -1


# 作者：灵茶山艾府
# 链接：https://leetcode.cn/problems/minimum-operations-to-maximize-last-elements-in-arrays/solutions/2523218/zhi-you-liang-chong-qing-kuang-pythonjav-jdeg/
# 来源：力扣（LeetCode）
# 著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
